import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TextInput, StyleSheet, ScrollView, TouchableOpacity, SafeAreaView, Image, Dimensions, NativeSyntheticEvent, NativeScrollEvent, StatusBar } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../../navigation/types';

const { width } = Dimensions.get('window');

const WritingScreen = () => {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const [selectedTab, setSelectedTab] = useState('论文');
  const [currentIndex, setCurrentIndex] = useState(0);
  const tabScrollViewRef = useRef<ScrollView>(null);
  const contentScrollViewRef = useRef<ScrollView>(null);

  // 功能卡片数据 - 修改成第二张图的布局
  const featureCards = [
    {
      id: 1,
      title: '文档转PPT',
      subTitle: '生成高级排版',
      iconColor: '#FFC1B6',
      iconType: 'P',
      route: 'PptGeneration' as keyof RootStackParamList
    },
    {
      id: 2,
      title: '课程报告',
      subTitle: '按格式一键生成',
      iconColor: '#96CEFF',
      iconType: '📊',
      route: 'CourseReport' as keyof RootStackParamList
    },
    {
      id: 3,
      title: '活动策划',
      subTitle: '助力实践活动',
      iconColor: '#FFD88A',
      iconType: '🎉',
      route: 'ActivityPlanning' as keyof RootStackParamList
    },
    {
      id: 4,
      title: '图片生成',
      subTitle: '定制化生成图片',
      iconColor: '#A6E9C8',
      iconType: '🖌️',
      route: 'AIImageGeneration' as keyof RootStackParamList
    },
    {
      id: 5,
      title: '改写润色',
      subTitle: '改词句优化表达',
      iconColor: '#95CAFA',
      iconType: '✏️',
      route: 'AITextGeneration' as keyof RootStackParamList
    },
    {
      id: 6,
      title: '有奖招募',
      subTitle: '来抢1000元现金',
      iconColor: '#FFBE99',
      iconType: '🎁',
      route: 'AITextGeneration' as keyof RootStackParamList
    }
  ];

  // 文档列表数据，根据每个标签页分组
  const documentsByTab: Record<string, Array<any>> = {
    '论文': [
      { id: 1, title: '标准论文格式参考建议.docx', uploader: '匿名用户', icon: 'W', iconColor: '#4285F4' },
      { id: 2, title: '会计学毕业论文专业毕业论文论文帮助会计专业毕业论文会计论文', uploader: 'Lily246', icon: 'P', iconColor: '#FF6B6B' },
      { id: 3, title: 'f0fe45d8bed126fff705cc17552707221820e593a', uploader: '我会努力', icon: 'P', iconColor: '#FF6B6B' },
      { id: 4, title: '毕业设计论文-毕业论文-论文资料-论文选题-GIS毕业论文题目', uploader: '蘑菇', icon: 'P', iconColor: '#FF6B6B' },
      { id: 5, title: '毕业论文论文', uploader: 'Cal', icon: 'P', iconColor: '#FF6B6B' },
      { id: 6, title: '计算机论文范文计算机论文', uploader: '几儿', icon: 'P', iconColor: '#FF6B6B' },
    ],
    'PPT模板': [
      { id: 1, title: '商务简约PPT模板.pptx', uploader: '设计达人', icon: 'P', iconColor: '#FF6B6B' },
      { id: 2, title: '毕业答辩PPT模板合集', uploader: 'PPT设计师', icon: 'P', iconColor: '#FF6B6B' },
      { id: 3, title: '创意图形排版PPT模板', uploader: '创意小王', icon: 'P', iconColor: '#FF6B6B' },
    ],
    '求职简历': [
      { id: 1, title: '简历模板合集.docx', uploader: '就业指导', icon: 'W', iconColor: '#4285F4' },
      { id: 2, title: '计算机专业求职简历模板', uploader: 'HR小王', icon: 'W', iconColor: '#4285F4' },
    ],
    '心得体会': [
      { id: 1, title: '实习心得体会范文', uploader: '职场新人', icon: 'W', iconColor: '#4285F4' },
      { id: 2, title: '读书心得模板', uploader: '阅读爱好者', icon: 'W', iconColor: '#4285F4' },
    ],
    '学习计划': [
      { id: 1, title: '大学四年学习计划', uploader: '学霸一号', icon: 'W', iconColor: '#4285F4' },
    ],
    '思想汇报': [
      { id: 1, title: '入党思想汇报2023', uploader: '组织部', icon: 'W', iconColor: '#4285F4' },
    ],
    '入党申请': [
      { id: 1, title: '入党申请书范文', uploader: '党员同志', icon: 'W', iconColor: '#4285F4' },
    ],
    '读后感': [
      { id: 1, title: '四大名著读后感合集', uploader: '文学爱好者', icon: 'W', iconColor: '#4285F4' },
    ],
    '更多': [
      { id: 1, title: '其他类型文档', uploader: '系统管理员', icon: 'W', iconColor: '#4285F4' },
    ],
  };

  // 顶部标签数据
  const topTabs = ['论文', 'PPT模板', '求职简历', '心得体会', '学习计划', '思想汇报', '入党申请', '读后感', '更多'];

  // 处理内容区域滑动事件
  const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    const scrollX = event.nativeEvent.contentOffset.x;
    const index = Math.round(scrollX / width);

    if (currentIndex !== index) {
      setCurrentIndex(index);
      setSelectedTab(topTabs[index]);

      // 确保标签栏滚动到可见区域
      if (tabScrollViewRef.current) {
        tabScrollViewRef.current.scrollTo({
          x: index * 80 - 100, // 根据实际宽度调整
          animated: true
        });
      }
    }
  };

  // 处理标签点击事件
  const handleTabPress = (tab: string, index: number) => {
    setSelectedTab(tab);
    setCurrentIndex(index);

    // 滚动内容区域到对应标签的内容
    if (contentScrollViewRef.current) {
      contentScrollViewRef.current.scrollTo({
        x: index * width,
        animated: true
      });
    }
  };

  // 处理功能卡片点击
  const handleFeatureCardPress = (card: { id: number; title: string; subTitle: string; iconType: string; iconColor: string; route?: keyof RootStackParamList }) => {
    if (card.route) {
      // @ts-ignore - 忽略类型错误，确保功能可用
      navigation.navigate(card.route);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* 搜索栏 */}
      <View style={styles.searchContainer}>
        <View style={styles.searchBar}>
          <Text style={styles.searchIcon}>🔍</Text>
          <Text style={styles.searchPlaceholder}>搜索AI功能和百万文库</Text>
        </View>
      </View>

      {/* 内容区域 */}
      <ScrollView style={styles.scrollView}>
        {/* AI写长文卡片 */}
        <View style={styles.aiLongWritingCard}>
          <View style={styles.aiLongWritingContent}>
            <Text style={styles.aiLongWritingTitle}>AI写长文</Text>
            <Text style={styles.aiLongWritingSubtitle}>单篇可生成1.5万字+参考文献</Text>
            <TouchableOpacity
              style={styles.writeNowButton}
              onPress={() => {
                // 确保正确跳转到AITextGeneration页面
                navigation.navigate('AITextGeneration');
              }}
            >
              <Text style={styles.writeNowButtonText}>立即写作</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.aiRobotContainer}>
            <Text style={styles.aiRobotIcon}>🤖</Text>
          </View>
        </View>

        {/* 功能卡片网格 - 新布局 */}
        <View style={styles.featuresContainer}>
          {featureCards.map((card) => (
            <TouchableOpacity
              key={card.id}
              style={styles.featureCard}
              onPress={() => handleFeatureCardPress(card)}
            >
              <View style={styles.featureContent}>
                <Text style={styles.featureTitle}>{card.title}</Text>
                <Text style={styles.featureSubtitle}>{card.subTitle}</Text>
              </View>
              <View style={[styles.featureIconContainer, { backgroundColor: card.iconColor }]}>
                <Text style={styles.featureIcon}>{card.iconType}</Text>
              </View>
            </TouchableOpacity>
          ))}
        </View>

        {/* 文档列表 - 修改样式，添加滑动功能 */}
        <View style={styles.documentsListContainer}>
          {/* 水平滚动标签栏 */}
          <View style={styles.docTabsScrollContainer}>
            <ScrollView
              ref={tabScrollViewRef}
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={styles.docTabsContentContainer}
            >
              {topTabs.map((tab, index) => (
                <TouchableOpacity
                  key={tab}
                  style={[styles.docTab, selectedTab === tab && styles.activeDocTab]}
                  onPress={() => handleTabPress(tab, index)}
                >
                  <Text style={[styles.docTabText, selectedTab === tab && styles.activeDocTabText]}>{tab}</Text>
                  {selectedTab === tab && <View style={styles.activeIndicator} />}
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>

          {/* 可滑动的内容区域 */}
          <ScrollView
            ref={contentScrollViewRef}
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            onScroll={handleScroll}
            scrollEventThrottle={16}
          >
            {topTabs.map((tab, tabIndex) => (
              <View key={tab} style={[styles.tabContent, { width }]}>
                {/* 文档列表项 */}
                {documentsByTab[tab].map((doc) => (
                  <View key={doc.id} style={styles.documentItemNew}>
                    <View style={[styles.documentIconContainer, {backgroundColor: '#F2F2F2'}]}>
                      <Text style={[styles.documentIconText, {color: doc.iconColor}]}>{doc.icon}</Text>
                    </View>
                    <View style={styles.documentInfoNew}>
                      <Text style={styles.documentTitleNew} numberOfLines={2}>{doc.title}</Text>
                      <Text style={styles.documentUploaderNew}>上传: {doc.uploader}</Text>
                    </View>
                  </View>
                ))}

                {/* "查看更多"按钮 */}
                <View style={styles.seeMoreButtonContainer}>
                  <TouchableOpacity style={styles.seeMoreButtonNew}>
                    <Text style={styles.seeMoreTextNew}>查看更多 ›</Text>
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          </ScrollView>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    marginTop:StatusBar.currentHeight || 0,
  },
  searchContainer: {
    padding: 10,
    backgroundColor: '#F5F5F5',
  },
  searchBar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
    borderRadius: 20,
    padding: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
  },
  searchIcon: {
    fontSize: 16,
    marginRight: 8,
    color: '#999999',
  },
  searchPlaceholder: {
    color: '#999999',
    fontSize: 14,
  },
  scrollView: {
    flex: 1,
  },
  // AI写长文卡片样式
  aiLongWritingCard: {
    margin: 15,
    backgroundColor: '#E6F0FF',
    borderRadius: 20,
    padding: 20,
    flexDirection: 'row',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  aiLongWritingContent: {
    flex: 1,
  },
  aiLongWritingTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 6,
  },
  aiLongWritingSubtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 15,
  },
  writeNowButton: {
    backgroundColor: '#FFFFFF',
    paddingVertical: 10,
    paddingHorizontal: 30,
    borderRadius: 30,
    alignSelf: 'flex-start',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
  },
  writeNowButtonText: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
  },
  aiRobotContainer: {
    width: 60,
    height: 60,
    justifyContent: 'center',
    alignItems: 'center',
  },
  aiRobotIcon: {
    fontSize: 40,
  },
  // 新的网格布局样式
  featuresContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    padding: 15,
    backgroundColor: '#FFFFFF',
    marginBottom: 10,
  },
  featureCard: {
    width: '48%',
    height: 80,
    backgroundColor: '#FFFFFF',
    borderRadius: 10,
    marginBottom: 15,
    padding: 15,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
  },
  featureContent: {
    flex: 1,
  },
  featureTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
  },
  featureSubtitle: {
    fontSize: 12,
    color: '#999',
  },
  featureIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
  },
  featureIcon: {
    fontSize: 20,
    color: '#FFFFFF',
  },
  // 文档列表新样式
  documentsListContainer: {
    backgroundColor: '#FFFFFF',
    paddingTop: 0,
    paddingBottom: 10,
  },
  // 文档标签栏样式
  docTabsScrollContainer: {
    borderBottomWidth: 1,
    borderBottomColor: '#EEEEEE',
  },
  docTabsContentContainer: {
    paddingHorizontal: 10,
  },
  docTab: {
    paddingVertical: 12,
    paddingHorizontal: 10,
    marginRight: 15,
    position: 'relative',
  },
  activeDocTab: {
    // 使用下划线指示器代替边框
  },
  docTabText: {
    fontSize: 15,
    color: '#666666',
  },
  activeDocTabText: {
    fontSize: 15,
    color: '#3478F6',
    fontWeight: 'bold',
  },
  activeIndicator: {
    position: 'absolute',
    bottom: -1,
    left: 0,
    right: 0,
    height: 2,
    backgroundColor: '#3478F6',
  },
  // 标签内容区样式
  tabContent: {
    // 使用屏幕宽度填充
  },
  documentItemNew: {
    flexDirection: 'row',
    paddingVertical: 12,
    paddingHorizontal: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: '#EEEEEE',
    alignItems: 'center',
  },
  documentIconContainer: {
    width: 32,
    height: 32,
    backgroundColor: '#F2F2F2',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
    marginRight: 10,
  },
  documentIconText: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  documentInfoNew: {
    flex: 1,
    justifyContent: 'center',
  },
  documentTitleNew: {
    fontSize: 14,
    color: '#333333',
    marginBottom: 4,
    lineHeight: 18,
  },
  documentUploaderNew: {
    fontSize: 12,
    color: '#999999',
  },
  seeMoreButtonContainer: {
    paddingVertical: 8,
    paddingHorizontal: 15,
    alignItems: 'center',
  },
  seeMoreButtonNew: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  seeMoreTextNew: {
    color: '#666666',
    fontSize: 13,
  },
});

export default WritingScreen;